import { observable, action } from 'mobx';
import { message } from 'antd';
import { WeaForm } from 'comsMobx';
import { WeaLocaleProvider } from 'ecCom';

import Api from '../apis/ops';

const getLabel = WeaLocaleProvider.getLabel;
const initalState = {
  loading: false,
  remind: 0,
  remark: 0,
  todoFields: [],
  remindTime: '',
  dealTime: '',
};
export default class TodoNewStore {
  @observable todoForm = new WeaForm();
  @observable loading = initalState.loading;
  @observable remind = initalState.remind; // 是否提醒
  @observable remark = initalState.remark; // 是否备注
  @observable todoFields = initalState.todoFields;
  @observable remindTime = initalState.remindTime; // 记录提醒设置--提醒时间
  @observable dealTime = initalState.dealTime;

  @action setStoreState = (params) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  };

  @action clear = () => this.setStoreState(initalState);

  @action getCondition = (params = {}) => {
    this.loading = true;
    Api.emailWaitdealCondition().then((res) => {
      this.todoForm.initFormFields(res.conditioninfo);
      this.todoFields = res.conditioninfo;
      let formParams = this.todoForm.getFormParams();
      this.remindTime = formParams.wdremindtime;
      this.dealTime = formParams.waitdealtime;
      if (Object.keys(params).length !== 0) {
        for (let attr in formParams) {
          // 赋值
          if (Object.prototype.hasOwnProperty.call(params, attr)) {
            this.todoForm.updateFields({ [attr]: { value: params[attr] } });
          }
        }
        this.remind = params.op_hasRemind == -1 ? 0 : params.op_hasRemind;
        this.remark = params.op_hasNote;
        this.remindTime = params.wdremindtime;
        this.dealTime = params.waitdealtime;
        if (params.op_hasRemind === 1) {
          this.todoForm.updateFields({
            waitdealway: {
              value: params.waitdealway === '' ? '5' : params.waitdealway,
            },
          });
        }
      }
      this.loading = false;
    });
  };

  @action saveTodo = async (params) => {
    this.loading = true;
    const res = await Api.saveTodo(params);
    try {
      if (res.status === '1') {
        message.success(getLabel(83551, '保存成功！'));
      } else {
        message.error(res.msg);
      }
    } catch (e) {
      message.error(e);
    }
    this.loading = false;
    return res;
  };

  @action setTodoComplete = async (params) => {
    this.loading = true;
    const res = await Api.setTodoComplete(params);
    try {
      if (res.status === '1') {
        message.success(getLabel(16746, '设置成功！'));
      } else {
        message.error(res.msg);
      }
    } catch (e) {
      message.error(e);
    }
    this.loading = false;
    return res;
  };
}
